package gulimall.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import gulimall.entity.Attr;
import gulimall.entity.AttrAttrgroupRelation;
import gulimall.entity.AttrGroup;
import gulimall.service.AttrAttrgroupRelationService;
import gulimall.service.AttrService;
import gulimall.service.IAttrGroupService;
import gulimall.service.ICategoryService;
import gulimall.utils.PageUtils;
import gulimall.utils.R;
import gulimall.vo.AttrGroupRelationVo;
import gulimall.vo.AttrGroupWithAttrVo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


/**
 * 属性分组
 *
 * @author HLF
 * @email 1132814637@qq.com
 * @date 2022-04-29 18:10:58
 */
@RestController
@RequestMapping("/product/attrgroup")
public class AttrGroupController {
    @Resource
    private IAttrGroupService attrGroupService;

    @Resource
    private ICategoryService categoryService;

    @Resource
    private AttrService attrService;

    @Resource
    private AttrAttrgroupRelationService relationService;


    /**
     * 获取属性分组的关联的所有属性
     * /product/attrgroup/{attrgroupId}/attr/relation
     * 响应数据：
     * <pre>
     * {
     *   "msg": "success",
     *   "code": 0,
     *   "data": [
     *     {
     *       "attrId": 4,
     *       "attrName": "aad",
     *       "searchType": 1,
     *       "valueType": 1,
     *       "icon": "qq",
     *       "valueSelect": "v;q;w",
     *       "attrType": 1,
     *       "enable": 1,
     *       "catelogId": 225,
     *       "showDesc": 1
     *     }
     *   ]
     * }
     * </pre>
     */
    @GetMapping("/{attrgroupId}/attr/relation")
    public R attrRelation(@PathVariable Long attrgroupId) {
        List<Attr> attrList = attrService.getRelationAttr(attrgroupId);
        return R.ok().put("data", attrList);
    }

    /**
     * 获取属性分组没有关联的其他属性
     * 接口描述:
     * 获取属性分组里面还没有关联的本分类里面的其他基本属性，方便添加新的关联
     * /product/attrgroup/{attrgroupId}/noattr/relation
     */
    @GetMapping("/{attrgroupId}/noattr/relation")
    public R noAttrRelation(@RequestParam Map<String, Object> params,
                            @PathVariable String attrgroupId) {
        PageUtils page = attrService.getNoRelationAttr(params, attrgroupId);

        return R.ok().put("page", page);
    }


    /**
     * 列表
     * 根据分类id查询分类的属性分组
     */
    @RequestMapping("/list/{catelogId}")
    //@RequiresPermissions("gulimall-product:attrgroup:list")
    public R list(@RequestParam Map<String, Object> params,
                  @PathVariable Long catelogId) {
        //PageUtils page = attrGroupService.queryPage(params);

        PageUtils page = attrGroupService.queryPage(params, catelogId);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{attrGroupId}")
    //@RequiresPermissions("gulimall-product:attrgroup:info")
    public R info(@PathVariable("attrGroupId") Long attrGroupId) {
        AttrGroup attrGroup = attrGroupService.getById(attrGroupId);

        Long catelogId = attrGroup.getCatelogId();
        List<Long> catIds = categoryService.getCatIdsByLeaf(catelogId);

        return R.ok().put("attrGroup", attrGroup).put("catIds", catIds);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    //@RequiresPermissions("gulimall-product:attrgroup:save")
    public R save(@RequestBody AttrGroup attrGroup) {
        attrGroupService.save(attrGroup);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("gulimall-product:attrgroup:update")
    public R update(@RequestBody AttrGroup attrGroup) {
        attrGroupService.updateById(attrGroup);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("gulimall-product:attrgroup:delete")
    public R delete(@RequestBody Long[] attrGroupIds) {
        attrGroupService.removeByIds(Arrays.asList(attrGroupIds));

        return R.ok();
    }

    /**
     * /product/attrgroup/attr/relation/delete
     * 删除属性与分组的关联关系
     * 请求的参数：
     * [{"attrId":1,"attrGroupId":2}]
     */
    @PostMapping("/attr/relation/delete")
    public R deleteRelation(@RequestBody List<AttrAttrgroupRelation> relationVoList) {
        attrGroupService.deleteRelation(relationVoList);
        return R.ok();
    }

    /**
     * 添加属性与分组关联关系(修改属性对应的分组)
     * /product/attrgroup/attr/relation
     * 请求参数：
     * [{
     * "attrGroupId": 0, //分组id
     * "attrId": 0, //属性id
     * }]
     */
    @PostMapping("/attr/relation")
    public R saveAttrRelation(@RequestBody List<AttrAttrgroupRelation> relations) {

        for (AttrAttrgroupRelation relation : relations) {
            AttrAttrgroupRelation one = relationService.getOne(new QueryWrapper<AttrAttrgroupRelation>()
                    .lambda().eq(AttrAttrgroupRelation::getAttrId, relation.getAttrId())
            );
            if (one != null) {
                if (one.getAttrGroupId() == null) {
                    //给查出来的relation对象赋值attrGroupId
                    one.setAttrGroupId(relation.getAttrGroupId());
                    relationService.update(relation, new UpdateWrapper<AttrAttrgroupRelation>()
                            .lambda().eq(AttrAttrgroupRelation::getAttrId, relation.getAttrId())
                    );
                }
            } else {
                relationService.save(relation);
            }
        }

        return R.ok();
    }

    /**
     * 获取分类下所有分组&关联属性
     * GET  /product/attrgroup/{catelogId}/withattr
     */
    @GetMapping("/{catelogId}/withattr")
    public R withAttr(@PathVariable Long catelogId) {
        List<AttrGroupWithAttrVo> attrGroupWithAttrVos = attrGroupService.getGroupWithAttrByCatelogId(catelogId);

        return R.ok().put("data", attrGroupWithAttrVos);
    }
}
